package view;

import javax.swing.JFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ImageIcon;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.WindowConstants;

import com.toedter.calendar.JDateChooserCellEditor;

import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Vector;

import services.DataCache;
import services.DataCache.eDataSections;
import services.MyTable;
/**
 * 
 * */
public class StartScreen extends JFrame implements Runnable {
	private static final long serialVersionUID = -4262436149855396749L;
	private CheckListTM tmTable;
	private MyTable table;
	private JButton btnDate;
	private static String outputExcel = "";
	
	public StartScreen() {
		tmTable = new CheckListTM();
		//iSelectedRow = 0;
		
		JScrollPane scrollPane = new JScrollPane();
		
		JToolBar toolBar = new JToolBar();
		toolBar.setFloatable(false);
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.TRAILING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
						.addComponent(scrollPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE)
						.addComponent(toolBar, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE))
					.addContainerGap())
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addComponent(toolBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
					.addContainerGap())
		);
		
		JButton btnAddRow = new JButton("");
		btnAddRow.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				Vector vTmpRow = new Vector();
				vTmpRow.add(""); //Region
				vTmpRow.add(""); //Course
				vTmpRow.add(""); //Pod
				vTmpRow.add(0); //Student
				vTmpRow.add(DataCache.dToday); //Start date
				vTmpRow.add(5); //Days
				vTmpRow.add("");
				vTmpRow.add("");
				tmTable.addRow_s(vTmpRow);
				}
		});
		
		btnDate = new JButton(DataCache.DateFormat.format(DataCache.dToday));
		btnDate.setToolTipText("Set start date");
		btnDate.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				final JButton btnTmp = (JButton) arg0.getSource();
				final MyDatePicker dpFrame = new MyDatePicker();
				dpFrame.setSize(new Dimension(620,420));
				dpFrame.setLocation(getLocation().x + (getSize().width - dpFrame.getSize().width) / 2,
						getLocation().y + (getSize().height - dpFrame.getSize().height) / 2);
				dpFrame.setDate(DataCache.dToday);
				
				dpFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
				dpFrame.addWindowListener(new WindowListener(){

					@Override
					public void windowActivated(WindowEvent arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowClosed(WindowEvent arg0) {
						// TODO Auto-generated method stub
						//System.out.println(arg0);
						DataCache.window_locker = false;
						DataCache.dToday = dpFrame.sDate;
						btnTmp.setText(DataCache.DateFormat.format(DataCache.dToday));
					}

					@Override
					public void windowClosing(WindowEvent arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowDeactivated(WindowEvent arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowDeiconified(WindowEvent arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowIconified(WindowEvent arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowOpened(WindowEvent arg0) {
						// TODO Auto-generated method stub
						
					}});
				if (!DataCache.window_locker){
					dpFrame.setVisible(true);
					DataCache.window_locker = true;
				}
			}
		});
		
		JButton btnReload = new JButton("");
		btnReload.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				File cf = new File(DataCache.sConfigFile);
				if (cf.exists()){
					cf.delete();
				}
				DataCache.reloadData(eDataSections.Configuration);
				DataCache.reloadData(eDataSections.CourseMatrix);
				DataCache.reloadData(eDataSections.VAMatrix);
				DataCache.reloadData(eDataSections.PBTemplate);
				DataCache.reloadData(eDataSections.Dictionary);
				DataCache.reloadData(eDataSections.NAM);
				DataCache.reloadData(eDataSections.ROW);
				btnDate.setText(DataCache.DateFormat.format(DataCache.dToday));
			}
		});
		btnReload.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/arrow-refresh-icon.png")));
		btnReload.setToolTipText("Refresh configuration");
		toolBar.add(btnReload);
		
		btnDate.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/date-icon.png")));
		toolBar.add(btnDate);
		toolBar.addSeparator();
		btnAddRow.setToolTipText("Add a new row");
		btnAddRow.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/add-icon.png")));
		toolBar.add(btnAddRow);
		
		JButton btnDeleteRow = new JButton("");
		btnDeleteRow.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				removeSelectedRows();		      
			}
		});
		btnDeleteRow.setToolTipText("Remove selected row");
		btnDeleteRow.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/delete-icon.png")));
		toolBar.add(btnDeleteRow);
		
		JButton btnAutowidthfix = new JButton("");
		btnAutowidthfix.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				/*
				Vector<Vector> vData = tmTable.getDataVector();
				Map<Integer, Integer> longestCell = new HashMap<Integer, Integer>();
				
				if (vData != null){
					for (int ir=0; ir<vData.size(); ir++){
						for (int ic=0; ic<vData.elementAt(ir).size(); ic++){
							if (longestCell.get(ic)!=null){
								if (longestCell.get(ic) < vData.elementAt(ir).elementAt(ic).toString().length()){
									longestCell.put(ic, vData.elementAt(ir).elementAt(ic).toString().length());
								}
							}
							else{
								longestCell.put(ic, vData.elementAt(ir).elementAt(ic).toString().length());
							}
						}
					}
				}
				
				for (int ic=0; ic<tmTable.getColumnCount(); ic++)
				{
					TableColumn column = table.getColumnModel().getColumn(ic);
					int iCellWidth = longestCell.get(ic) * 8;
					if (ic==3||ic==5){
						iCellWidth = 70;
					}
					if (ic==4){iCellWidth =  135;}
					column.setPreferredWidth(iCellWidth);
					System.out.println("Width set to:" + iCellWidth);
				}*/
				
				table.pack(0, true);
				if (table.getSize().width > getSize().width && table.getSize().width < DataCache.screenDim.width){
					setSize(table.getSize().width, getSize().height);
					if (getLocation().x != (DataCache.screenDim.width - getSize().width) /2 ){
						setLocation((DataCache.screenDim.width - getSize().width) /2, getLocation().y);
					}
				}				
			}
		});
		btnAutowidthfix.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/Actions-zoom-fit-width-icon.png")));
		btnAutowidthfix.setToolTipText("Auto fit width");
		toolBar.add(btnAutowidthfix);
		toolBar.addSeparator();
		
		JButton btnCleanAll = new JButton("");
		btnCleanAll.setToolTipText("Create an empty table");
		btnCleanAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				DataCache.vIP.removeAllElements();
				while (tmTable.getRowCount()>0){
					tmTable.removeRow(0);
				}
			}
		});
		btnCleanAll.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/page-icon.png")));
		toolBar.add(btnCleanAll);
		
		JButton btnLoad = new JButton("");
		btnLoad.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser oFileDia = new JFileChooser();
				oFileDia.setDialogTitle("Load pod booking.");
				//oFileDia.setSelectedFile(new java.io.File(DataCache.sdfFileNamePrefix.format(DataCache.dToday)+"-PodBooking.xlsx"));
				oFileDia.setFileFilter(new FileNameExtensionFilter("Excel 2007 or later workwook (.xlsx)", "xlsx"));
				int reVal = oFileDia.showOpenDialog(StartScreen.this);
				if (reVal == JFileChooser.APPROVE_OPTION){
					if (DataCache.loadPBFile(oFileDia.getSelectedFile().getAbsolutePath()))
						for (int i=0; i<DataCache.vIP.size(); i++){
							tmTable.addRow_s(DataCache.vIP.elementAt(i));
					}					
				}
			}
		});
		btnLoad.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/folder-icon.png")));
		btnLoad.setToolTipText("Load pod booking");
		toolBar.add(btnLoad);
		
		JButton btnExport = new JButton("");
		btnExport.setToolTipText("Save as a new pod booking .xslx file");
		toolBar.add(btnExport);
		btnExport.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				DataCache.vIP.removeAllElements();
				DataCache.vIP.addAll(tmTable.getDataVector());
				JFileChooser oFileDia = new JFileChooser();
				oFileDia.setDialogTitle("Save pod booking.");
				oFileDia.setSelectedFile(new java.io.File(DataCache.sdfFileNamePrefix.format(DataCache.dToday)+"-PodBooking.xlsx"));
				oFileDia.setFileFilter(new FileNameExtensionFilter("Excel 2007 or later workwook (.xlsx)", "xlsx"));
				int reVal = oFileDia.showSaveDialog(StartScreen.this);
				if (reVal == JFileChooser.APPROVE_OPTION){
					outputExcel = oFileDia.getSelectedFile().getAbsolutePath();
					File chkBeforeSav = new File(outputExcel);
					if (chkBeforeSav.exists()){
						Object[] options = {"No", "Yes"};
						int n = JOptionPane.showOptionDialog(new JFrame(),
								"File " + oFileDia.getSelectedFile().getAbsolutePath() + " exists, \n" +
										"overwrite it?",
								"File found",
								JOptionPane.YES_NO_OPTION,
								JOptionPane.QUESTION_MESSAGE,
							    null,     //do not use a custom Icon
							    options,  //the titles of buttons
							    options[0]); //default button title
						if (n>0){
							
							DataCache.savePBFile(outputExcel);
						}
					}
					else{
						DataCache.savePBFile(outputExcel);
					}
				}

			}
		});
		btnExport.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/action-save-icon.png")));
		toolBar.addSeparator();
		
		JButton btnGo = new JButton("");
		btnGo.setToolTipText("Generate from IP");
		btnGo.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					DataCache.generateIPSheet(DataCache.DateFormat.parse(btnDate.getText()));
				} catch (ParseException e) {
					DataCache.generateIPSheet(DataCache.dToday);
					e.printStackTrace();
				}
				while (tmTable.getRowCount()>0){
					tmTable.removeRow(0);
				}
				if (!DataCache.vIP.isEmpty())
					for (int i=0; i<DataCache.vIP.size(); i++){
						tmTable.addRow_s(DataCache.vIP.elementAt(i));
				}
			}
		});
		btnGo.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/icon-component-icon.png")));
		toolBar.add(btnGo);
		
		final JButton btnCourseInfo = new JButton("");
		btnCourseInfo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				final JFrame fcinfo = new JFrame();
				//DataCache.debug(243, DataCache.vCourseCache);
				CourseInfoPanel cip = new CourseInfoPanel();
				cip.setCourseItems();
				fcinfo.setSize(new Dimension(655,495));
				fcinfo.setMinimumSize(new Dimension(655,495));
				fcinfo.setMaximumSize(new Dimension(655,495));
				fcinfo.setUndecorated(true);
				fcinfo.setLocation(getLocation().x + (getSize().width - fcinfo.getSize().width) / 2,
						getLocation().y + (getSize().height - fcinfo.getSize().height) / 2);				
				fcinfo.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
				fcinfo.getContentPane().add(cip);
				cip.btnClose.addActionListener(new ActionListener(){

					@Override
					public void actionPerformed(ActionEvent arg0) {
						// TODO Auto-generated method stub
						fcinfo.dispose();
					}
					
				});
				fcinfo.addWindowListener(new WindowListener(){
					@Override
					public void windowActivated(WindowEvent e) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowClosed(WindowEvent e) {
						// TODO Auto-generated method stub
						DataCache.window_locker = false;
						btnCourseInfo.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/book-icon.png")));
					}

					@Override
					public void windowClosing(WindowEvent e) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowDeactivated(WindowEvent e) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowDeiconified(WindowEvent e) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowIconified(WindowEvent e) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void windowOpened(WindowEvent e) {
						// TODO Auto-generated method stub
						
					}
					
				});
				if (!DataCache.window_locker){
					fcinfo.setVisible(true);
					DataCache.window_locker = true;
					btnCourseInfo.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/book-open-icon.png")));
				}
			}
		});
		btnCourseInfo.setToolTipText("Look up course information");
		btnCourseInfo.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/book-icon.png")));
		toolBar.add(btnCourseInfo);
		
		
		JButton btnRunexcel = new JButton("");
		btnRunexcel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					//Desktop.getDesktop().open(new File("/Applications/Microsoft Office 2011/Microsoft Excel.app"));
					if (!outputExcel.isEmpty()){
						Desktop.getDesktop().open(new File(outputExcel));
					}
					
					//Runtime.getRuntime().exec();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				
			}
		});
		btnRunexcel.setToolTipText("Run Excel");
		btnRunexcel.setIcon(new ImageIcon(StartScreen.class.getResource("/resources/Excel-icon.png")));
		toolBar.add(btnRunexcel);
		
		table = new MyTable();
		table.setModel(tmTable);
		table.setRowHeight(35);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		table.setFont(new Font("Arial", Font.PLAIN, 15));
		
		//region 0
		JComboBox locComboBox = new JComboBox();
		locComboBox.setModel(new DefaultComboBoxModel(DataCache.sRegion));		
		locComboBox.setEditable(true);
		table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(locComboBox));
				
		//Course
		/*final JComboBox comboBoxPod = new JComboBox();
		comboBoxPod.setEditable(true);
		JComboBox cmComboBox = new JComboBox();
		cmComboBox.setEditable(true);
		cmComboBox.setModel(new DefaultComboBoxModel(DataCache.vCourseName));
		cmComboBox.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				JComboBox comboTemp = (JComboBox) arg0.getSource();
				String strSelected = comboTemp.getSelectedItem().toString();
				
				for (int ir=0; ir<DataCache.vCourseCache.size(); ir++){
					if (strSelected.compareTo(DataCache.vCourseCache.elementAt(ir).elementAt(1).toString()) == 0){
						DataCache.arrayPodName = DataCache.vCourseCache.elementAt(ir).elementAt(4).toString().split(",");
					}
				}
				
    			if (DataCache.arrayPodName != null)
    	    	{
    	    		for (int i=0; i<DataCache.arrayPodName.length; i++)
    	    		{
    	    			DataCache.arrayPodName[i] = DataCache.arrayPodName[i].trim().toUpperCase();
    	    			Pattern p1 = Pattern.compile("^([0-9]+)$");
    					Matcher m = p1.matcher(DataCache.arrayPodName[i]);
    					while (m.find())
    					{
    						if(m.group(1).length() == 1){
    							DataCache.arrayPodName[i] = "POD0" + m.group(1);
    						}
    						else {
    							DataCache.arrayPodName[i] = "POD" + m.group(1);
    						}
    					}
    					p1 = Pattern.compile("^SYM(.*)");
    					m = p1.matcher(DataCache.arrayPodName[i]);
    					while (m.find())
    					{
    						DataCache.arrayPodName[i] = m.group(1);
    					}

    	    		}
    	    		comboBoxPod.setModel(new DefaultComboBoxModel(DataCache.arrayPodName));
    	    	}
			}
			
		});
		table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(cmComboBox));
*/
		JTextField courseNameEditor = new JTextField();
		courseNameEditor.addFocusListener(new FocusListener(){

			@Override
			public void focusGained(FocusEvent arg0) {
				// TODO Auto-generated method stub
			}

			@Override
			public void focusLost(FocusEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		courseNameEditor.getDocument().addDocumentListener(new DocumentListener(){

			@Override
			public void changedUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void insertUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void removeUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		//CourseNameCellRender cncr = new CourseNameCellRender();
		//CourseNameCellEditor cnce = new CourseNameCellEditor();
		//table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(courseNameEditor));
		//table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new JTextField()));
		//table.getColumnModel().getColumn(1).setCellEditor(cnce);
		//table.getColumnModel().getColumn(1).setCellRenderer(cncr);
		//Pod
		//table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(comboBoxPod));
		
		//Start Date
		//table.getColumnModel().getColumn(4).setCellEditor(new DatePickerCellEditor());
		table.getColumnModel().getColumn(4).setCellEditor(new JDateChooserCellEditor());
		table.getColumnModel().getColumn(4).setCellRenderer(new DateCellRender());
				
		//Instructor
		table.getColumnModel().getColumn(7).setCellEditor(new DefaultCellEditor(new JTextField()));	
		table.setCellEditor(new DefaultCellEditor(new JTextField()));
		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		
		scrollPane.setViewportView(table);
		getContentPane().setLayout(groupLayout);
	}
	private void removeSelectedRows(){
		CheckListTM tableModel = (CheckListTM) table.getModel();
		
		int rows[] = table.getSelectedRows();
		for (int hasRow=0; hasRow<rows.length; hasRow++){
			if (hasRow != tmTable.getRowCount() -1){
				tableModel.removeRow(rows[hasRow] - hasRow);
			}else{
				tableModel.removeRow(rows[hasRow]);
			}
		}
		table.clearSelection();
		
	}

	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		/*for (int i=0; i<DataCache.vCourseCache.size(); i++)
		{
			System.out.println(DataCache.vCourseName.elementAt(i));
		}*/
		setTitle("Pod Booking Helper \tv" + DataCache._version);
		setSize(new Dimension(650,650));
		setVisible(true);
	}
}